<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>单词消消乐 - 新词汇</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Comic Sans MS', 'Microsoft YaHei', sans-serif;
        }
        
        body {
            background: linear-gradient(to bottom, #fff9c4, #ffecb3);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 20px;
            overflow-x: hidden;
            position: relative;
            cursor: pointer;
        }
        
        /* 派对装饰元素 */
        .decoration {
            position: absolute;
            z-index: -1;
        }
        
        .decoration.balloon {
            width: 40px;
            height: 60px;
            border-radius: 50%;
            opacity: 0.7;
            animation: float 8s infinite ease-in-out;
        }
        
        .decoration.confetti {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            opacity: 0.8;
            animation: fall 10s infinite linear;
        }
        
        .header {
            text-align: center;
            margin: 10px 0 20px;
            width: 100%;
            position: relative;
        }
        
        h1 {
            font-size: 3.5rem;
            color: #ff6f00;
            text-shadow: 3px 3px 0 #ffcc80, 6px 6px 0 rgba(0,0,0,0.1);
            letter-spacing: 2px;
            margin-bottom: 10px;
            background: linear-gradient(to right, #ff6f00, #ff8f00);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            position: relative;
            display: inline-block;
            animation: bounce 2s infinite;
        }
        
        h1::after {
            content: "";
            position: absolute;
            bottom: -10px;
            left: 50%;
            transform: translateX(-50%);
            width: 80%;
            height: 6px;
            background: linear-gradient(to right, #ff6f00, #ffcc80);
            border-radius: 50%;
            filter: blur(2px);
        }
        
        .game-info {
            display: flex;
            justify-content: space-around;
            width: 95%;
            max-width: 800px;
            margin-bottom: 20px;
            padding: 12px 20px;
            background: rgba(255, 255, 255, 0.7);
            border-radius: 18px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            backdrop-filter: blur(5px);
        }
        
        .info-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            font-size: 1.2rem;
            font-weight: bold;
            color: #ff6f00;
        }
        
        .info-value {
            margin-top: 5px;
            background: #ffcc80;
            padding: 4px 12px;
            border-radius: 15px;
            min-width: 80px;
            text-align: center;
            font-size: 1.3rem;
        }
        
        .game-container {
            display: grid;
            grid-template-columns: repeat(6, 1fr);
            gap: 16px;
            width: 95%;
            max-width: 800px;
            min-height: 350px;
            perspective: 1000px;
            margin: 0 auto;
        }
        
        .bubble {
            width: 100%;
            aspect-ratio: 1/1;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            font-size: 1.4rem;
            font-weight: bold;
            cursor: pointer;
            user-select: none;
            transition: transform 0.3s, box-shadow 0.3s;
            text-align: center;
            padding: 10px;
            box-shadow: 
                inset 0 -8px 15px rgba(0,0,0,0.2),
                inset 0 8px 15px rgba(255,255,255,0.7),
                0 10px 20px rgba(0,0,0,0.15);
            position: relative;
            overflow: hidden;
            animation: float 4s infinite ease-in-out;
            will-change: transform;
        }
        
        .bubble::before {
            content: "";
            position: absolute;
            top: 10%;
            left: 20%;
            width: 25%;
            height: 25%;
            background: rgba(255,255,255,0.6);
            border-radius: 50%;
        }
        
        .bubble:hover {
            transform: scale(1.05) translateY(-5px);
        }
        
        .bubble.selected {
            transform: scale(1.1);
            box-shadow: 
                inset 0 -8px 15px rgba(0,0,0,0.2),
                inset 0 8px 15px rgba(255,255,255,0.7),
                0 0 0 4px #ffeb3b,
                0 15px 25px rgba(0,0,0,0.2);
            animation: pulse 0.5s;
        }
        
        .bubble.matched {
            animation: pop 0.2s forwards;
        }
        
        /* 匹配反馈弹窗通用样式 */
        .feedback-toast {
            position: fixed;
            top: 20%;
            left: 50%;
            transform: translate(-50%, -50%);
            padding: 12px 24px;
            border-radius: 30px;
            font-size: 1.5rem;
            font-weight: bold;
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
            z-index: 80;
            opacity: 0;
            pointer-events: none;
            transition: all 0.3s ease;
            text-shadow: 1px 1px 2px rgba(0,0,0,0.2);
        }
        
        /* 成功弹窗：绿色渐变 */
        .toast-success {
            background: linear-gradient(135deg, #4CAF50, #8BC34A);
            color: white;
        }
        
        /* 错误弹窗：红色渐变 */
        .toast-error {
            background: linear-gradient(135deg, #F44336, #EF5350);
            color: white;
        }
        
        /* 鼓励弹窗：蓝色渐变 */
        .toast-encourage {
            background: linear-gradient(135deg, #2196F3, #03A9F4);
            color: white;
        }
        
        /* 弹窗显示动画 */
        .feedback-toast.show {
            opacity: 1;
            transform: translate(-50%, 0);
            animation: bounceToast 0.8s ease;
        }
        
        .success-screen {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.8);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            z-index: 100;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.5s;
        }
        
        .success-screen.show {
            opacity: 1;
            pointer-events: all;
        }
        
        .success-content {
            background: linear-gradient(135deg, #fff9c4, #ffecb3);
            padding: 30px;
            border-radius: 25px;
            text-align: center;
            max-width: 500px;
            width: 90%;
            box-shadow: 0 20px 40px rgba(0,0,0,0.4);
            transform: scale(0.8);
            transition: transform 0.5s;
            position: relative;
            overflow: hidden;
        }
        
        .success-screen.show .success-content {
            transform: scale(1);
        }
        
        .success-content::before {
            content: "🎉";
            position: absolute;
            top: -30px;
            left: -30px;
            font-size: 5rem;
            opacity: 0.3;
            z-index: -1;
        }
        
        .success-content::after {
            content: "🎂";
            position: absolute;
            bottom: -40px;
            right: -40px;
            font-size: 6rem;
            opacity: 0.3;
            z-index: -1;
        }
        
        .success-content h2 {
            font-size: 2.5rem;
            color: #ff6f00;
            margin-bottom: 15px;
            text-shadow: 2px 2px 0 #ffcc80;
        }
        
        .success-content p {
            font-size: 1.6rem;
            color: #5d4037;
            margin: 20px 0;
            font-weight: bold;
        }
        
        .next-btn {
            background: linear-gradient(to right, #ff6f00, #ff8f00);
            color: white;
            border: none;
            padding: 12px 35px;
            font-size: 1.4rem;
            border-radius: 50px;
            cursor: pointer;
            margin-top: 15px;
            box-shadow: 0 5px 15px rgba(255, 111, 0, 0.4);
            transition: transform 0.3s, box-shadow 0.3s;
            font-weight: bold;
            letter-spacing: 1px;
        }
        
        .next-btn:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 20px rgba(255, 111, 0, 0.6);
        }
        
        .next-btn:active {
            transform: translateY(0);
        }
        
        .instructions {
            background: rgba(255, 255, 255, 0.85);
            border-radius: 15px;
            padding: 12px;
            margin-top: 20px;
            max-width: 800px;
            width: 95%;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        .instructions h3 {
            color: #ff6f00;
            margin-bottom: 8px;
            text-align: center;
            font-size: 1.3rem;
        }
        
        .instructions p {
            color: #5d4037;
            line-height: 1.5;
            text-align: center;
            font-size: 1rem;
        }
        
        .music-control {
            position: fixed;
            top: 15px;
            right: 15px;
            background: rgba(255, 255, 255, 0.8);
            border-radius: 50%;
            width: 45px;
            height: 45px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            box-shadow: 0 3px 10px rgba(0,0,0,0.2);
            z-index: 10;
        }
        
        .music-control i {
            font-size: 1.5rem;
            color: #ff6f00;
        }
        
        /* 首次交互提示 */
        .interaction-prompt {
            position: fixed;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(255, 111, 0, 0.9);
            color: white;
            padding: 10px 20px;
            border-radius: 20px;
            font-size: 1rem;
            box-shadow: 0 3px 10px rgba(0,0,0,0.2);
            z-index: 50;
            opacity: 0;
            transition: opacity 0.3s;
            pointer-events: none;
        }
        
        .interaction-prompt.show {
            opacity: 1;
        }
        
        /* 弹窗弹跳动画 */
        @keyframes bounceToast {
            0% { transform: translate(-50%, -20px); opacity: 0; }
            50% { transform: translate(-50%, 5px); }
            100% { transform: translate(-50%, 0); opacity: 1; }
        }
        
        @keyframes float {
            0%, 100% { transform: translateY(0); }
            50% { transform: translateY(-10px); }
        }
        
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.15); }
            100% { transform: scale(1.1); }
        }
        
        @keyframes pop {
            0% { transform: scale(1); opacity: 1; }
            50% { transform: scale(1.2); opacity: 0.7; }
            100% { transform: scale(0); opacity: 0; }
        }
        
        @keyframes bounce {
            0%, 100% { transform: translateY(0); }
            50% { transform: translateY(-10px); }
        }
        
        @keyframes fall {
            0% { transform: translateY(-100px) rotate(0deg); opacity: 0; }
            10% { opacity: 1; }
            90% { opacity: 1; }
            100% { transform: translateY(100vh) rotate(360deg); opacity: 0; }
        }
        
        @keyframes bgPulse {
            0% { background: linear-gradient(to bottom, #fff9c4, #ffecb3); }
            100% { background: linear-gradient(to bottom, #fff9c4, #ffe082); }
        }
        
        @media (max-width: 768px) {
            h1 {
                font-size: 2.8rem;
            }
            
            .game-container {
                grid-template-columns: repeat(3, 1fr);
                gap: 12px;
                max-width: 500px;
            }
            
            .bubble {
                font-size: 1.3rem;
            }
            
            .info-item {
                font-size: 1.1rem;
            }
            
            .info-value {
                font-size: 1.2rem;
                min-width: 70px;
            }
            
            /* 移动端弹窗适配 */
            .feedback-toast {
                font-size: 1.2rem;
                padding: 10px 20px;
            }
        }
        
        @media (max-width: 480px) {
            h1 {
                font-size: 2.2rem;
            }
            
            .game-info {
                flex-direction: column;
                gap: 8px;
                padding: 10px;
            }
            
            .info-item {
                flex-direction: row;
                gap: 10px;
            }
            
            .info-value {
                margin-top: 0;
            }
            
            .bubble {
                font-size: 1.1rem;
            }
            
            .success-content h2 {
                font-size: 2rem;
            }
            
            .success-content p {
                font-size: 1.4rem;
            }
        }
    </style>
</head>
<body>
    <div class="music-control" id="musicControl">
        <i class="fas fa-music"></i>
    </div>
    
    <!-- 首次交互提示 -->
    <div class="interaction-prompt" id="interactionPrompt">
        点击任意位置开始播放音乐
    </div>
    
    <!-- 反馈弹窗：成功+错误+鼓励 -->
    <div class="feedback-toast toast-success" id="successToast">匹配成功！🎉</div>
    <div class="feedback-toast toast-error" id="errorToast">匹配错误，请重试！❌</div>
    <div class="feedback-toast toast-encourage" id="encourageToast">太棒了！继续加油！👍</div>
    
    <div class="header">
        <h1>单词消消乐</h1>
    </div>
    
    <div class="game-info">
        <div class="info-item">
            <span>当前轮次:</span>
            <div class="info-value" id="round">1/3</div>
        </div>
        <div class="info-item">
            <span>用时:</span>
            <div class="info-value" id="time">00:00</div>
        </div>
        <div class="info-item">
            <span>匹配:</span>
            <div class="info-value" id="matches">0/9</div>
        </div>
    </div>
    
    <div class="game-container" id="gameContainer"></div>
    
    <div class="success-screen" id="successScreen">
        <div class="success-content">
            <h2 id="successTitle">恭喜你挑战成功！</h2>
            <p>本轮用时: <span id="finalTime">00:00</span></p>
            <p id="roundInfo">第1轮完成</p>
            <button class="next-btn" id="nextBtn">继续挑战</button>
        </div>
    </div>
    
    <div class="instructions">
        <h3>游戏说明</h3>
        <p>点击两个泡泡，如果它们对应的意思互相匹配（如"restaurant"和"饭店"），则泡泡会消失；否则，泡泡会保持原状。点击泡泡时会播放单词发音和音效。完成三轮挑战后，游戏结束！</p>
    </div>
    
    <!-- 音效资源 -->
    <audio id="popSound" preload="auto">
        <source src="assets/audio/popSound.mp3" type="audio/mpeg">
     </audio>
    <audio id="successSound" preload="auto">
        <source src="assets/audio/successSound.mp3" type="audio/mpeg">
      </audio>
    <audio id="errorSound" preload="auto">
        <source src="assets/audio/errorSound.mp3" type="audio/mpeg">
      </audio>
    <!-- 新增鼓励音效 -->
    <audio id="encourageSound" preload="auto">
        <source src="assets/audio/encourageSound.mp3" type="audio/mpeg">
      </audio>
    <audio id="roundCompleteSound" preload="auto">
        <source src="assets/audio/roundCompleteSound.mp3" type="audio/mpeg">
      
    <audio id="allCompleteSound" preload="auto">
        <source src="assets/audio/allCompleteSound.mp3" type="audio/mpeg">
      
    
    <!-- 背景音乐 -->
    <audio id="bgMusic" loop preload="auto">
        <source src="assets/audio/bgMusic.mp3" type="audio/mpeg">
      
    
    <!-- 单词发音音频容器（动态创建音频元素） -->
    <div id="pronunciationContainer"></div>
    
    <script>
        // 核心修改1：替换为新的单词对
        const wordPairs = [
            { en: "restaurant", cn: "饭店🏨", enAudio: "assets/audio/words/restaurant.mp3", cnAudio: "assets/audio/words/fandian.mp3" },
            { en: "hospital", cn: "医院🏥", enAudio: "assets/audio/words/hospital.mp3", cnAudio: "assets/audio/words/yiyuan.mp3" },
            { en: "supermarket", cn: "超市🛒", enAudio: "assets/audio/words/supermarket.mp3", cnAudio: "assets/audio/words/chaoshi.mp3" },
            { en: "park", cn: "公园🌳", enAudio: "assets/audio/words/park.mp3", cnAudio: "assets/audio/words/gongyuan.mp3" },
            { en: "toy store", cn: "玩具店🧸", enAudio: "assets/audio/words/toystore.mp3", cnAudio: "assets/audio/words/wanjudian.mp3" },
            { en: "bookstore", cn: "书店📚", enAudio: "assets/audio/words/bookstore.mp3", cnAudio: "assets/audio/words/shudian.mp3" },
            { en: "gift", cn: "礼物🎁", enAudio: "assets/audio/words/gift.mp3", cnAudio: "assets/audio/words/liwu.mp3" },
            { en: "card", cn: "卡片💳", enAudio: "assets/audio/words/card.mp3", cnAudio: "assets/audio/words/kapian.mp3" },
            { en: "toy", cn: "玩具🧸", enAudio: "assets/audio/words/toy.mp3", cnAudio: "assets/audio/words/wanju.mp3" },
            { en: "cupcake", cn: "纸杯蛋糕🧁", enAudio: "assets/audio/words/cupcake.mp3", cnAudio: "assets/audio/words/zhibeidangao.mp3" },
            { en: "balloon", cn: "气球🎈", enAudio: "assets/audio/words/balloon.mp3", cnAudio: "assets/audio/words/qiqiu.mp3" },
            { en: "party", cn: "派对🎉", enAudio: "assets/audio/words/party.mp3", cnAudio: "assets/audio/words/paidui.mp3" },
            { en: "lake", cn: "湖泊🏞️", enAudio: "assets/audio/words/lake.mp3", cnAudio: "assets/audio/words/hupo.mp3" },
            { en: "cake", cn: "蛋糕🎂", enAudio: "assets/audio/words/cake.mp3", cnAudio: "assets/audio/words/dangao.mp3" },
            { en: "cape", cn: "披风🧥", enAudio: "assets/audio/words/cape.mp3", cnAudio: "assets/audio/words/pifeng.mp3" }
        ];
        
        // 游戏状态变量
        let selectedBubbles = [];
        let matchedPairs = 0;
        let startTime = null;
        let timerInterval = null;
        let currentPairs = [];
        let currentRound = 1;
        let totalRounds = 3;
        let musicPlaying = false;
        let totalTime = 0;
        let userInteracted = false;
        // 跟踪已播放的鼓励音效
        let encouragementPlayed = {
            3: false,
            6: false,
            9: false
        };
        // 存储当前正在播放的发音音频（避免重叠）
        let currentPronunciationAudio = null;
        
        // DOM 元素
        const gameContainer = document.getElementById('gameContainer');
        const timeDisplay = document.getElementById('time');
        const matchesDisplay = document.getElementById('matches');
        const roundDisplay = document.getElementById('round');
        const successScreen = document.getElementById('successScreen');
        const successTitle = document.getElementById('successTitle');
        const finalTimeDisplay = document.getElementById('finalTime');
        const roundInfo = document.getElementById('roundInfo');
        const nextBtn = document.getElementById('nextBtn');
        const popSound = document.getElementById('popSound');
        const successSound = document.getElementById('successSound');
        const errorSound = document.getElementById('errorSound');
        const encourageSound = document.getElementById('encourageSound');
        const roundCompleteSound = document.getElementById('roundCompleteSound');
        const allCompleteSound = document.getElementById('allCompleteSound');
        const bgMusic = document.getElementById('bgMusic');
        const musicControl = document.getElementById('musicControl');
        const interactionPrompt = document.getElementById('interactionPrompt');
        const successToast = document.getElementById('successToast');
        const errorToast = document.getElementById('errorToast');
        const encourageToast = document.getElementById('encourageToast');
        const pronunciationContainer = document.getElementById('pronunciationContainer');
        
        // 创建派对装饰
        function createDecorations() {
            const colors = ['#ff6f69', '#ffcc5c', '#88d8b0', '#96ceb4', '#ffeead', '#ff6b6b'];
            
            // 气球装饰
            for (let i = 0; i < 15; i++) {
                const balloon = document.createElement('div');
                balloon.className = 'decoration balloon';
                balloon.style.background = `radial-gradient(circle at 30% 30%, ${colors[i % colors.length]}aa, ${colors[(i+3) % colors.length]})`;
                balloon.style.left = `${Math.random() * 100}%`;
                balloon.style.top = `${Math.random() * 100}%`;
                balloon.style.animationDelay = `${Math.random() * 5}s`;
                document.body.appendChild(balloon);
            }
            
            // 彩纸装饰
            for (let i = 0; i < 30; i++) {
                const confetti = document.createElement('div');
                confetti.className = 'decoration confetti';
                confetti.style.background = colors[i % colors.length];
                confetti.style.left = `${Math.random() * 100}%`;
                confetti.style.animationDelay = `${Math.random() * 5}s`;
                confetti.style.animationDuration = `${5 + Math.random() * 10}s`;
                document.body.appendChild(confetti);
            }
        }
        
        // 核心修改2：播放单词发音（先停止当前发音，再播放新发音）
        function playWordPronunciation(wordText, lang) {
            // 1. 停止当前正在播放的发音（避免重叠）
            if (currentPronunciationAudio) {
                currentPronunciationAudio.pause();
                currentPronunciationAudio.remove();
                currentPronunciationAudio = null;
            }
            
            // 2. 找到当前单词对应的音频路径
            let audioPath = '';
            const targetWord = wordPairs.find(pair => {
                return (lang === 'en' && pair.en === wordText) || (lang === 'cn' && pair.cn === wordText);
            });
            
            if (targetWord) {
                audioPath = lang === 'en' ? targetWord.enAudio : targetWord.cnAudio;
            }
            
            // 3. 创建并播放发音音频
            if (audioPath) {
                const audio = document.createElement('audio');
                audio.src = audioPath;
                audio.preload = 'auto';
                pronunciationContainer.appendChild(audio);
                
                // 播放发音（播放完成后移除元素）
                audio.play().catch(e => {
                    console.log(`单词发音播放失败: ${e.message}`);
                    audio.remove();
                });
                
                audio.onended = () => {
                    audio.remove();
                    currentPronunciationAudio = null;
                };
                
                currentPronunciationAudio = audio;
            }
        }
        
        // 初始化游戏
        function initGame() {
            selectedBubbles = [];
            matchedPairs = 0;
            startTime = null;
            gameContainer.innerHTML = '';
            matchesDisplay.textContent = '0/9';
            roundDisplay.textContent = `${currentRound}/${totalRounds}`;
            currentPairs = getRandomPairs(9);
            createBubbles();
            roundInfo.textContent = `第${currentRound}轮完成`;
            // 重置本轮鼓励音效播放状态
            encouragementPlayed = {
                3: false,
                6: false,
                9: false
            };
            // 重置发音音频
            if (currentPronunciationAudio) {
                currentPronunciationAudio.pause();
                currentPronunciationAudio.remove();
                currentPronunciationAudio = null;
            }
        }
        
        // 随机选择单词对
        function getRandomPairs(count) {
            const shuffled = [...wordPairs].sort(() => 0.5 - Math.random());
            return shuffled.slice(0, count);
        }
        
        // 创建单词泡泡（新增：为泡泡绑定语言标识，用于发音播放）
        function createBubbles() {
            const allWords = [];
            const colors = ['#ff6f69', '#ffcc5c', '#88d8b0', '#96ceb4', '#ffeead', '#ff6b6b'];
            
            // 生成中英文单词对数组（新增：携带语言信息）
            currentPairs.forEach(pair => {
                allWords.push({ 
                    text: pair.en, 
                    pairId: pair.en, 
                    lang: 'en',  // 英文标识
                    audioPath: pair.enAudio 
                });
                allWords.push({ 
                    text: pair.cn, 
                    pairId: pair.en, 
                    lang: 'cn',  // 中文标识
                    audioPath: pair.cnAudio 
                });
            });
            
            // 随机排序
            shuffleArray(allWords);
            
            // 创建泡泡元素
            allWords.forEach((word, index) => {
                const bubble = document.createElement('div');
                bubble.className = 'bubble';
                bubble.textContent = word.text;
                bubble.dataset.pairId = word.pairId;
                bubble.dataset.lang = word.lang;  // 存储语言类型
                bubble.dataset.text = word.text;  // 存储单词文本
                bubble.dataset.index = index;
                
                // 随机颜色
                const color = colors[Math.floor(Math.random() * colors.length)];
                bubble.style.background = `radial-gradient(circle at 30% 30%, ${color}bb, ${color})`;
                bubble.style.color = '#333';
                
                // 点击事件（核心修改：先播放发音，再执行游戏逻辑）
                bubble.addEventListener('click', () => handleBubbleClick(bubble));
                
                // 浮动动画延迟
                bubble.style.animationDelay = `${index * 0.1}s`;
                
                gameContainer.appendChild(bubble);
            });
        }
        
        // 核心修改3：泡泡点击处理（先播放单词发音，再执行原有逻辑）
        function handleBubbleClick(bubble) {
            // 1. 触发音乐播放（首次交互）
            if (!userInteracted) {
                triggerMusicPlay();
            }
            
            // 2. 忽略已匹配或已选中的泡泡
            if (bubble.classList.contains('matched') || bubble.classList.contains('selected') || selectedBubbles.length >= 2) {
                return;
            }
            
            // 3. 播放单词发音（核心新增）
            const wordText = bubble.dataset.text;
            const wordLang = bubble.dataset.lang;
            playWordPronunciation(wordText, wordLang);
            
            // 4. 播放点击音效（原有逻辑）
            playSound(popSound);
            
            // 5. 开始计时（首次点击）
            if (startTime === null) {
                startTime = new Date();
                startTimer();
            }
            
            // 6. 添加到选中列表
            bubble.classList.add('selected');
            selectedBubbles.push(bubble);
            
            // 7. 选中两个泡泡时判断匹配结果
            if (selectedBubbles.length === 2) {
                // 暂时禁用所有泡泡点击（避免快速点击问题）
                disableAllBubbles();
                
                const [bubble1, bubble2] = selectedBubbles;
                
                if (bubble1.dataset.pairId === bubble2.dataset.pairId) {
                    // 匹配成功
                    playSound(successSound);
                    showToast(successToast);
                    
                    setTimeout(() => {
                        bubble1.classList.add('matched');
                        bubble2.classList.add('matched');
                        bubble1.classList.remove('selected');
                        bubble2.classList.remove('selected');
                        selectedBubbles = [];
                        
                        // 更新匹配计数
                        matchedPairs++;
                        matchesDisplay.textContent = `${matchedPairs}/9`;
                        
                        // 检查是否需要播放鼓励音效（每3个匹配）
                        checkEncouragement();
                        
                        // 重新启用点击
                        enableAllBubbles();
                        
                        // 检查是否完成本轮
                        if (matchedPairs === 9) {
                            endRound();
                        }
                    }, 200); // 与泡泡消失动画同步
                } else {
                    // 匹配错误
                    playSound(errorSound);
                    showToast(errorToast);
                    
                    setTimeout(() => {
                        bubble1.classList.remove('selected');
                        bubble2.classList.remove('selected');
                        selectedBubbles = [];
                        // 重新启用点击
                        enableAllBubbles();
                    }, 800);
                }
            }
        }
        
        // 新增：禁用所有未匹配泡泡的点击（解决快速点击问题）
        function disableAllBubbles() {
            const bubbles = document.querySelectorAll('.bubble:not(.matched)');
            bubbles.forEach(bubble => {
                bubble.style.pointerEvents = 'none';
            });
        }
        
        // 新增：启用所有未匹配泡泡的点击
        function enableAllBubbles() {
            const bubbles = document.querySelectorAll('.bubble:not(.matched)');
            bubbles.forEach(bubble => {
                bubble.style.pointerEvents = 'auto';
            });
        }
        
        // 检查是否需要播放鼓励音效（每3个匹配）
        function checkEncouragement() {
            if ((matchedPairs === 3 && !encouragementPlayed[3]) || 
                (matchedPairs === 6 && !encouragementPlayed[6])) {
                
                const messages = [
                    "太棒了！继续加油！👍",
                    "真厉害！保持势头！💪",
                    "太优秀了！不要停！🚀",
                    "好样的！继续前进！👏"
                ];
                
                const randomMessage = messages[Math.floor(Math.random() * messages.length)];
                encourageToast.textContent = randomMessage;
                
                playSound(encourageSound);
                showToast(encourageToast);
                
                encouragementPlayed[matchedPairs] = true;
            }
        }
        
        // 通用音效播放函数
        function playSound(audioElement) {
            audioElement.currentTime = 0; // 重置播放位置（支持连续播放）
            audioElement.play().catch(e => console.log(`音效播放失败: ${e.message}`));
        }
        
        // 通用弹窗显示函数（自动隐藏）
        function showToast(toastElement) {
            // 先隐藏所有弹窗，避免重叠
            successToast.classList.remove('show');
            errorToast.classList.remove('show');
            encourageToast.classList.remove('show');
            
            // 显示目标弹窗
            toastElement.classList.add('show');
            
            // 1.5秒后自动隐藏
            setTimeout(() => {
                toastElement.classList.remove('show');
            }, 1500);
        }
        
        // 背景音乐控制
        function triggerMusicPlay() {
            if (!musicPlaying) {
                bgMusic.play()
                    .then(() => {
                        musicPlaying = true;
                        musicControl.innerHTML = '<i class="fas fa-pause"></i>';
                        hideInteractionPrompt();
                    })
                    .catch(e => {
                        console.log("音乐播放需要用户交互:", e);
                        showInteractionPrompt();
                    });
            }
            userInteracted = true;
        }
        
        // 交互提示显示/隐藏
        function showInteractionPrompt() {
            interactionPrompt.classList.add('show');
            setTimeout(hideInteractionPrompt, 5000);
        }
        
        function hideInteractionPrompt() {
            interactionPrompt.classList.remove('show');
        }
        
        // 计时器功能
        function startTimer() {
            clearInterval(timerInterval);
            timerInterval = setInterval(() => {
                const elapsedTime = Math.floor((new Date() - startTime) / 1000);
                const minutes = Math.floor(elapsedTime / 60).toString().padStart(2, '0');
                const seconds = (elapsedTime % 60).toString().padStart(2, '0');
                timeDisplay.textContent = `${minutes}:${seconds}`;
            }, 1000);
        }
        
        // 结束本轮游戏
        function endRound() {
            clearInterval(timerInterval);
            const elapsedTime = Math.floor((new Date() - startTime) / 1000);
            totalTime += elapsedTime;
            
            // 格式化时间显示
            const formatTime = (timeInSeconds) => {
                const minutes = Math.floor(timeInSeconds / 60).toString().padStart(2, '0');
                const seconds = (timeInSeconds % 60).toString().padStart(2, '0');
                return `${minutes}:${seconds}`;
            };
            
            // 播放对应音效
            if (currentRound < totalRounds) {
                playSound(roundCompleteSound);
            } else {
                playSound(allCompleteSound);
            }
            
            // 更新结束界面
            finalTimeDisplay.textContent = formatTime(elapsedTime);
            if (currentRound < totalRounds) {
                successTitle.textContent = `恭喜完成第${currentRound}轮！`;
                nextBtn.textContent = "继续挑战";
            } else {
                successTitle.textContent = "恭喜完成所有挑战！";
                roundInfo.textContent = `总用时: ${formatTime(totalTime)}`;
                nextBtn.textContent = "重新开始";
            }
            
            // 显示结束弹窗
            setTimeout(() => {
                successScreen.classList.add('show');
            }, 1000);
        }
        
        // 数组随机排序
        function shuffleArray(array) {
            for (let i = array.length - 1; i > 0; i--) {
                const j = Math.floor(Math.random() * (i + 1));
                [array[i], array[j]] = [array[j], array[i]];
            }
            return array;
        }
        
        // 下一轮/重新开始按钮
        nextBtn.addEventListener('click', () => {
            userInteracted = true;
            hideInteractionPrompt();
            successScreen.classList.remove('show');
            
            if (currentRound < totalRounds) {
                currentRound++;
            } else {
                currentRound = 1;
                totalTime = 0;
            }
            
            initGame();
            triggerMusicPlay();
        });
        
        // 音乐控制按钮
        musicControl.addEventListener('click', () => {
            userInteracted = true;
            hideInteractionPrompt();
            
            if (musicPlaying) {
                bgMusic.pause();
                musicControl.innerHTML = '<i class="fas fa-music"></i>';
            } else {
                bgMusic.play().catch(e => console.log("背景音乐播放失败:", e));
                musicControl.innerHTML = '<i class="fas fa-pause"></i>';
            }
            musicPlaying = !musicPlaying;
        });
        
        // 全局点击触发音乐（任意区域）
        document.addEventListener('click', () => {
            if (!musicPlaying) {
                triggerMusicPlay();
            }
            userInteracted = true;
        });
        
        // 触摸设备支持
        document.addEventListener('touchstart', () => {
            if (!userInteracted) {
                triggerMusicPlay();
            }
        }, { passive: true });
        
        // 页面加载初始化
        window.addEventListener('DOMContentLoaded', () => {
            createDecorations();
            initGame();
            
            // 离线Font Awesome图标
            const style = document.createElement('style');
            style.textContent = `
                .fas {
                    font-family: 'Font Awesome 5 Free';
                    font-weight: 900;
                }
                .fa-music:before { content: "\\f001"; }
                .fa-pause:before { content: "\\f04c"; }
            `;
            document.head.appendChild(style);
            
            // 尝试自动播放背景音乐
            setTimeout(triggerMusicPlay, 100);
        });
    </script>
</body>
</html>